package com.huluobo.a2203kotlinjetpackdemo.paging

import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import androidx.paging.Pager
import androidx.paging.PagingConfig
import androidx.paging.PagingData
import androidx.paging.cachedIn
import kotlinx.coroutines.flow.Flow

/**
 *  Created by LC on 2024/7/22.
 *  Paging的viewModel层和Repo层
 */
class PagingViewMode : ViewModel() {
    fun getPagingData(): Flow<PagingData<Bean>> {
        return Repo.getPagingData().cachedIn(viewModelScope)//数据缓存到viewModel的协程作用域
    }
}

object Repo {
    const val PAGE_SIZE = 5
    private val apiService = ApiService.create()

    fun getPagingData(): Flow<PagingData<Bean>> {
        //prefetchDistance 表示距离底部多少条数据开始预加载
        //设置为0表示滑动到底部才进行加载,默认值是当前分页的大小,当前是5
        //如果想让用户对加载无感,则适当增加这个值即可,比如现在咱们设置的5倍大小
        //pagingSourceFactory 数据加载的工厂,直接放之前写的数据源即可
        //flow 让数据源行程一个flow流,可以给页面发送
        return Pager(
            config = PagingConfig(pageSize = PAGE_SIZE, prefetchDistance = PAGE_SIZE * 5),
            pagingSourceFactory = {
                RepoPagingSource(apiService)
            }
        ).flow
    }
}